package com.qph.base.security.realm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

import com.qph.base.security.entity.Permission;
import com.qph.base.security.entity.Role;
import com.qph.base.security.entity.User;
import com.qph.base.security.service.IUserService;
import com.qph.utils.base.StringUtil;


public class AuthRealm extends AuthorizingRealm {

	@Resource(name="userService")
	private IUserService userService;


	// 验证当前Subject（可理解为当前用户）所拥有的权限，且给其授权。
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		if (principals == null) {
			throw new AuthorizationException("Principal对象不能为空");
		}
		// 获取当前登录的用户名
		User user =  (User) principals.getPrimaryPrincipal();
		//用户角色
		List<Role> roleList = (List<Role>) user.getRoles();
		Set<String> permissions = new HashSet<String>();
		Set<String> roles = new HashSet<String>();
		for (Role role : roleList) {
			roles.add(role.getId());
			List<Permission> perList = (List<Permission>) role.getPmss();
			if (perList == null || perList.size() == 0){
				continue;
			}
			for (Permission pmss : role.getPmss()) {
				
				if (!pmss.getPermission().isEmpty())
				
				permissions.add(pmss.getPermission());
			}
		}
		//用户权限
		List<Permission> pmsList = (List<Permission>) user.getPmss();
		for (Permission pmss : pmsList) {
			if (!pmss.getPermission().isEmpty())
			permissions.add(pmss.getPermission());
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 给当前用户设置角色
		info.addRoles(roles);
		// 给当前用户设置权限
		info.addStringPermissions(permissions);
		return info;
	}

	// 认证回调函数,登录时调用.
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String userName = token.getUsername();

		if (StringUtil.isEmpty(userName)) {
			throw new AccountException("用户名不能为空！");
		}

		User user = userService.getUserByUsername(userName);

		if (user == null) {
			throw new UnknownAccountException("用户不存在");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
				user, user.getPassword(), user.getNickname());
		return info;
	}

	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principal, getName());
		clearCachedAuthorizationInfo(principals);
	}
}
